package edu.sctu.zhuyingzhi.month201506.day20150616.httpTest;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by user13 on 2015/6/16.
 */
public  class  HttpConnection {
    public static void getconnection(String path,HashMap<String,String> mapParam) throws IOException {

        URL url = new URL(path);

        int count;
        byte[] buffer = new byte[1024*1024];
        String param = getparam(mapParam);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);


//        urlConnection.setRequestProperty("Content-Type", "text/html");
//        urlConnection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
//        urlConnection.setRequestProperty("Charset", "UTF-8");

        urlConnection.connect();

        OutputStream outputstram =  urlConnection.getOutputStream();
        outputstram.write(param.getBytes());

        outputstram.close();



        InputStream inputStream = urlConnection.getInputStream();

        File file = new File("D://haha.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file);



        while((count = inputStream.read(buffer))!=-1){
            fileOutputStream.write(buffer);
            System.out.println(new String(buffer,0,count,"utf-8"));


        }
        System.out.println();
        inputStream.close();
    }

    public static String getparam(HashMap<String,String> map){
        Iterator iterator = map.entrySet().iterator();
        String param="";
        while(iterator.hasNext()){
            Map.Entry<String, String> entry= (Map.Entry<String, String>) iterator.next();
            param = param + entry.getKey()+"="+entry.getValue()+"&";
        }
        param = param.substring(0,param.length()-1);//什么意思
        return param;
    }
}
